package com.zgg.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created DingdingUtil.java
 *
 * @author liyang
 * @create 2018-04-20
 **/
public class DingdingUtil {
    private static final Logger logger = Logger.getLogger(DingdingUtil.class);

    /**
     * 钉钉机器人发送消息（现在不支持附件）
     *
     * @param webhookToken //钉钉群机器人的webhook(找要发送群的群主要,请在DingDingConstant类中补充)
     * @param subject      //科目类型
     * @param message      //发送内容
     */
    public static void dingDingChatbotSend(String webhookToken, String subject, String message, List<String> mobile) {
        String formatDate;
        try {
            //格式 24小时制：2016-07-06 09:39:58
            Date date = new Date();
            DateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //HH表示24小时制；
            formatDate = dFormat.format(date);

            //判断是否有webhook
            if (webhookToken != null && !"".equals(webhookToken)) {
                logger.info("开始向钉钉群发送消息------" + subject);
                HttpClient httpclient = HttpClients.createDefault();
                HttpPost httppost = new HttpPost(webhookToken);
                httppost.addHeader("Content-Type", "application/json; charset=utf-8");

                JSONObject messageJson = new JSONObject();
                messageJson.put("title", subject);
                messageJson.put("text", subject + "\n:" + message + "\n> ###### " + formatDate + "发布  \n");
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("msgtype", "markdown");
                jsonObject.put("markdown", messageJson);
                jsonObject.put("isAtAll", true);
                if (!mobile.isEmpty()) {
                    JSONObject mobileJson = new JSONObject();
                    mobileJson.put("atMobiles", JSONArray.toJSON(mobile));
                    jsonObject.put("at", mobileJson);
                }

                //String textMsg = "{\"msgtype\": \"markdown\", " + "\"markdown\": {\"title\":\"" + subject + "\",\"text\": \"" + subject + "\n:" + message + "\n> ###### " + formatDate + "发布  \n\"}," + "\"isAtAll\": \"true\"}";
                StringEntity se = new StringEntity(jsonObject.toString(), "utf-8");
                httppost.setEntity(se);
                HttpResponse response = null;
                response = httpclient.execute(httppost);
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    String result = EntityUtils.toString(response.getEntity(), "utf-8");
                    logger.info(result);
                }
                logger.error("消息发送完毕------" + subject);
            } else {
                logger.error("消息发送失败，请检查群机器人的webhook！！");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
